<template>
  <div ref="chart" :style="{ width, height }"></div>
</template>

<script>
// 引入 ECharts
const echarts = require("echarts");
// 引入防抖函数
import { debounce } from 'lodash-es';

export default {
  props: {
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    option: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      myChart: null,
      resizeObserver: null,
      isMounted: false, // 组件挂载状态标记
      isDestroyed: false // 组件销毁状态标记
    };
  },
  mounted() {
    this.$nextTick(() => {
      try {
        // 确保图表容器存在
        if (!this.$refs.chart) {
          console.error("图表容器元素未找到");
          return;
        }

        if (echarts) {
          // 初始化图表实例
          this.myChart = echarts.init(this.$refs.chart);
          // 初始化图表配置
          this.myChart.setOption(this.option, { notMerge: true });
          
          // 标记组件已挂载
          this.isMounted = true;

          // 定义防抖处理函数（移除parentElement相关逻辑）
          const handleResize = debounce(() => {
            // 多重安全检查：组件未销毁+已挂载+图表实例有效
            if (this.isDestroyed || !this.isMounted || !this.myChart || this.myChart.isDisposed()) {
              return;
            }
            try {
              // 仅执行resize重绘，不修改宽度（宽度由props控制）
              this.myChart.resize();
            } catch (error) {
              console.warn("ECharts resize 失败:", error);
            }
          }, 300);

          // 创建ResizeObserver（观察自身容器，避免依赖parentElement）
          this.resizeObserver = new ResizeObserver(handleResize);
          this.resizeObserver.observe(this.$refs.chart);
        }
      } catch (error) {
        console.error("初始化ECharts实例时出错:", error);
      }
    });
  },
  methods: {
    getEchartsInstance() {
      // 确保返回有效的实例
      if (this.myChart && !this.myChart.isDisposed()) {
        return this.myChart;
      }
      return null;
    },
    // 暴露一个安全的resize方法供父组件调用
    safeResize() {
      if (this.myChart && !this.myChart.isDisposed() && !this.isDestroyed) {
        try {
          this.myChart.resize();
        } catch (error) {
          console.warn("手动调用resize失败:", error);
        }
      }
    }
  },
  beforeDestroy() {
    // 标记组件已销毁
    this.isDestroyed = true;
    this.isMounted = false;
    
    // 清理工作
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
      this.resizeObserver = null;
    }
    if (this.myChart && !this.myChart.isDisposed()) {
      this.myChart.dispose();
      this.myChart = null;
    }
  },
  watch: {
    option: {
      handler(newOption) {
        // 检查实例是否有效且组件未销毁
        if (this.myChart && !this.myChart.isDisposed() && !this.isDestroyed) {
          try {
            this.myChart.setOption(newOption, { notMerge: true });
          } catch (error) {
            console.warn("更新ECharts配置失败:", error);
          }
        }
      },
      deep: true,
      immediate: true,
    }
  },
};
</script>

<style scoped>
div {
  box-sizing: border-box;
}
</style>